package com.wish.nettysimple;

import com.wish.common.MyUtils;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;


/**
 * @author tantexian
 * @since 2016/7/11
 */
public class NettyClient {

    public static void main(String[] args) {
        new NettyClient().connect(MyUtils.getDefaultServerAddr(), MyUtils.getDefaultPort());
    }


    public void connect(String host, int port) {
        // 关于使用方式请参考NettyRobotServer注释
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new RobotClientHandle());
                }
            });

            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    class RobotClientHandle extends ChannelHandlerAdapter {

        private ByteBuf sendMsgBuffer;


        RobotClientHandle() {
            String msg = "what is you name?";
            this.send(msg);
        }


        public void send(String msg) {
            byte[] bytes = msg.getBytes();
            sendMsgBuffer = Unpooled.buffer(bytes.length);
            sendMsgBuffer.writeBytes(bytes);

        }


        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {

            ctx.writeAndFlush(sendMsgBuffer);
        }


        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf byteBuf = (ByteBuf) msg;
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);
            String body = new String(bytes, "UTF-8");
            System.out.println(body);
        }


        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }
    }

}
